<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    :title="`${dataRef?.roleDesc ?? ''}的可写表单域`"
    width="800px"
    :canFullscreen="false"
    @ok="handleOk"
  >
    <Card
      title="可写表单域"
      :bodyStyle="{ padding: '20px' }"
      :bordered="false"
      style="margin: 0 20px"
    >
      <InputTextArea :rows="3" disabled v-model:value="dataRef.fieldNames" />
      <a @click="handleSelectFormDomian">选择表单域</a>
    </Card>
    <SelectFormDomainModal
      @register="registerSelectFormDomainModal"
      @success="handleSuccessSelectFormDomainModal"
    />
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useModal } from '/@/components/Modal';
  import { Card, Input } from 'ant-design-vue';
  import SelectFormDomainModal from './SelectFormDomainModal.vue';

  export default defineComponent({
    name: 'FormDomainModal',
    components: { BasicModal, Card, InputTextArea: Input.TextArea, SelectFormDomainModal },
    emits: ['success', 'register'],
    setup(props, { emit }) {
      const dataRef = ref<Recordable>({});
      const formCode = ref('');
      const type = ref(-1);
      const [register, { closeModal, setModalProps }] = useModalInner((data) => {
        console.log('data', data);
        dataRef.value = data?.record ? Object.assign({}, data?.record) : {};
        formCode.value = data?.formCode;
        type.value = data.index;
      });
      const { t } = useI18n();

      async function handleOk() {
        try {
          setModalProps({ confirmLoading: true });

          emit('success', unref(dataRef), unref(type));
          closeModal();
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      const [registerSelectFormDomainModal, { openModal }] = useModal();

      const handleSelectFormDomian = () => {
        openModal(true, {
          formCode: unref(formCode),
          fields: dataRef.value.fields ? dataRef.value.fields.split(',') : [],
          type: unref(type),
        });
      };
      //表单域回显
      const handleSuccessSelectFormDomainModal = ({ fields, fieldTexts }) => {
        dataRef.value.fields = fields;
        dataRef.value.fieldNames = fieldTexts;
      };
      return {
        t,
        register,
        handleOk,
        registerSelectFormDomainModal,
        handleSuccessSelectFormDomainModal,
        handleSelectFormDomian,
        dataRef,
      };
    },
  });
</script>
